﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using B10.Models;
using System.Net;
using B10.Helpers;
using System.Text;
using Microsoft.Security.Application;
using B10.Properties;
using ManagedFusion.Web;
using Telerik.Web.Mvc;

namespace B10.Controllers
{
    [Authorize]
    [HandleError]
    public class PageController : Controller
    {
        IDatabaseRepository _db;

        public PageController()
            : this(new DatabaseRepository())
        {
        }

        public PageController(IDatabaseRepository db)
        {
            _db = db;
        }

        //
        // GET: /UserPage/

        public ActionResult Index()
        {
            return RedirectToAction("Create");
        }

        #region create

        //
        // GET: /UserPage/Create

        public ActionResult Create()
        {
            UserPage page = new UserPage();
            page.AllowComments = true;
            return View(new UserPageFormViewModel(page));
        }

        //
        // POST: /UserPage/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            UserPage page = new UserPage();
            UpdateModel(page, "Page");
            page.Title = Server.HtmlEncode(page.Title);
            page.Keywords = Server.HtmlEncode(page.Keywords);
            page.Description = Server.HtmlEncode(page.Description);
            page.Content = null;
            UpdateCategories(page, collection);
            if (ModelState.IsValid)
            {
                try
                {
                    if (UserHelper.UserId.HasValue)
                        page.ProfileId = UserHelper.UserId.Value;
                    page.Url = Url.GetValidUrlFromString(page.Title);
                    page.CreatedDate = DateTime.Now;
                    _db.Add(page);
                    _db.Save();
                    if (Request.Files.Count == 1 && Request.Files[0].ContentLength > 0
                    && ImageHelper.IsCorrectContentType(Request.Files[0].ContentType))
                    {
                        page.Thumbnail = ImageHelper.SaveThumbnail(Request.Files[0], page.Id);
                    }
                    _db.Save();
                    return RedirectToAction("EditContent", new { id = page.Id });
                }
                catch
                {
                    //TODO: log
                    throw;
                }
            }
            return View(new UserPageFormViewModel(page));
        }

        #endregion

        #region edit

        //
        // GET: /UserPage/Edit/5

        public ActionResult Edit(int id)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId) || page.Status == PageStatus.Accepted)
                return new ForbiddenResult();
            return View(new UserPageFormViewModel(page));
        }

        //
        // POST: /UserPage/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId) || page.Status == PageStatus.Accepted)
                return new ForbiddenResult();
            UpdateModel(page, "Page");
            page.Title = Server.HtmlEncode(page.Title);
            page.Keywords = Server.HtmlEncode(page.Keywords);
            page.Description = Server.HtmlEncode(page.Description);
            UpdateCategories(page, collection);
            if (ModelState.IsValid)
            {
                page.Url = Url.GetValidUrlFromString(page.Title);
                if (Request.Files.Count == 1 && Request.Files[0].ContentLength > 0
                    && ImageHelper.IsCorrectContentType(Request.Files[0].ContentType))
                {
                    page.Thumbnail = ImageHelper.SaveThumbnail(Request.Files[0], id);
                }
                _db.Save();
                return RedirectToAction("EditContent", new { id = page.Id });
            }
            return View(new UserPageFormViewModel(page));
        }



        public ActionResult EditContent(int id)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId) || page.Status == PageStatus.Accepted)
                return new ForbiddenResult();
            return View(page);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditContent(int id, FormCollection collection)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId) || page.Status == PageStatus.Accepted)
                return new ForbiddenResult();
            try
            {
                if (collection.AllKeys.Contains("Content"))
                {
                    page.Content = AntiXssHtmlHelper.GetSafeHtml(collection["Content"]);
                    _db.Save();
                }
                return RedirectToAction("Publish", new { id = page.Id });
            }
            catch
            {
                return View(page);
            }
        }

        #endregion

        #region publish

        public ActionResult Publish(int id)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId))
                return new ForbiddenResult();
            return View(page);
        }

        [CaptchaValidation]
        [HttpPost]
        public ActionResult Publish(int id, FormCollection collection)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return new FileNotFoundResult();
            if (!page.IsOwner(UserHelper.UserId))
                return new ForbiddenResult();
            if (ModelState.IsValid)
            {
                page.Status = PageStatus.Published;
                page.PublishDate = DateTime.Now;
                _db.Save();
                return View("PostPublish");
                //return RedirectToAction("Page", "Home", new { pageUrl = page.Url, id = page.Id });
            }
            return View(page);
        }

        #endregion

        #region delete

        [GridAction]
        public void Delete(int id)
        {
            UserPage page = _db.GetPage(id);
            if (page == null)
                return;
            if (!page.IsOwner(UserHelper.UserId) || page.Status == PageStatus.Accepted)
                return;
            _db.Delete<UserPage>(page);
            _db.Save();
        }

        #endregion

        #region private methods

        private void UpdateCategories(UserPage page, FormCollection collection)
        {
            try
            {
                string s = collection["SelectedCategories"];
                if (!String.IsNullOrEmpty(s))
                {
                    string[] ct = s.Split(',');
                    if (ct != null && ct.Length > 0 && ct.Length <= 3)
                    {
                        page.Category = (Categories)Int32.Parse(ct[0]);
                        if (ct.Length > 1)
                            page.Category2 = (Categories)Int32.Parse(ct[1]);
                        else
                            page.Category2 = null;
                        if (ct.Length > 2)
                            page.Category3 = (Categories)Int32.Parse(ct[2]);
                        else
                            page.Category3 = null;
                        return;
                    }
                }
            }
            catch { }
            ModelState.AddModelError("SelectedCategories",
                B10.Properties.ValidationMessages.Categories);

        }

        #endregion

        protected override void HandleUnknownAction(string actionName)
        {
            throw new HttpException((int)HttpStatusCode.NotFound, "Not Found");
        }
    }
}
